#ifndef DATAMONITORING_H
#define DATAMONITORING_H

#include <QWidget>
#include <QTimer>
#include <QtCharts>
#include <QLineSeries>
#include <QStandardItemModel>
#include "databasemanager.h"
#include "systemsetting.h"

QT_BEGIN_NAMESPACE
namespace Ui { class DataMonitoring; }
QT_END_NAMESPACE

class DataMonitoring : public QWidget
{
    Q_OBJECT

public:
    explicit DataMonitoring(QWidget *parent = nullptr);
    ~DataMonitoring();

    void setCurrentDevice(int deviceId);
    void populateDeviceComboBox();

private slots:
    void updateRealtimeData();
    void togglePause();
    void queryHistoryData();
    void exportData();
    void onDeviceChanged(int index);
    void onIntervalChanged(int value);

public slots:
    void startDataRefresh();
    void stopDataRefresh();

private:
    void setupRealtimeChart();
    void setupHistoryChart();
    void updateHistoryChart();
    void triggerAlarm(int deviceId, const QString &content);
    QVector<QPointF> fetchRealtimeData();
    QVector<QPair<QDateTime, QPair<double, double>>> fetchHistoryData(const QDateTime& start, const QDateTime& end);
    QStringList parseQueryResponse(const QString &response);

    Ui::DataMonitoring *ui;
    QTimer *m_realtimeTimer;
    QStandardItemModel *m_historyModel;
    QChart *m_realtimeChart;
    QChart *m_historyChart;
    QLineSeries *m_tempSeries;
    QLineSeries *m_humiditySeries;
    bool m_isPaused = false;
    int m_updateInterval = 2000;
    QTimer *m_refreshTimer;
    int m_currentDeviceId = -1;
    DatabaseManager* dbManager;
};

#endif // DATAMONITORING_H
